import requests
from typing import Dict
import os

class AlertService:
    """警报通知服务"""
    
    def __init__(self):
        self.webhook_url = os.getenv('ALERT_WEBHOOK_URL', '')
        self.email_enabled = os.getenv('EMAIL_ENABLED', 'false').lower() == 'true'
    
    def send_alert(self, detection_result: Dict):
        """发送警报"""
        message = self._format_alert_message(detection_result)
        
        # 发送到Webhook（如钉钉、企业微信）
        if self.webhook_url:
            self._send_webhook(message)
        
        # 发送邮件（需要配置）
        if self.email_enabled:
            self._send_email(message)
        
        print(f"⚠️ 警报: {message}")
    
    def _format_alert_message(self, result: Dict) -> str:
        """格式化警报消息"""
        count = result.get('count', 0)
        risk_level = result.get('risk_level', 'unknown')
        items = result.get('detected_items', [])
        
        message = f"""
🚨 敏感数据检测警报 🚨

风险等级: {risk_level.upper()}
检测数量: {count}
检测类型: {result.get('type', 'unknown')}

检测到的敏感信息:
"""
        for i, item in enumerate(items[:5], 1):  # 只显示前5个
            message += f"{i}. {item.get('type')}: {item.get('content', '')[:20]}...\n"
        
        if len(items) > 5:
            message += f"... 还有 {len(items) - 5} 项\n"
        
        return message
    
    def _send_webhook(self, message: str):
        """发送Webhook通知"""
        try:
            data = {
                "msgtype": "text",
                "text": {
                    "content": message
                }
            }
            requests.post(self.webhook_url, json=data, timeout=5)
        except Exception as e:
            print(f"Webhook发送失败: {e}")
    
    def _send_email(self, message: str):
        """发送邮件通知（需要实现）"""
        # TODO: 实现邮件发送功能
        pass

